import java.util.TreeSet;
import java.util.Iterator;
import java.util.Set;

public class StudentSetExample {
    public static void main(String[] args) {
        Set<Student> studentSet = new TreeSet<>();

        // 添加学生对象到集合中
        studentSet.add(new Student("Alice", 20));
        studentSet.add(new Student("Bob", 22));
        studentSet.add(new Student("Charlie", 18));
        studentSet.add(new Student("David", 21));

        System.out.println("学生集合中的人数：" + studentSet.size());
        System.out.println("学生集合中的学生信息：" + studentSet);

        // 添加重复的学生对象，查看插入结果
        boolean isIn = studentSet.add(new Student("Bob", 22));
        System.out.println("插入重复的学生对象是否成功：" + isIn);

        // 判断学生对象是否在集合中
        System.out.println("学生集合中是否包含Bob：" + studentSet.contains(new Student("Bob", 22)));
        System.out.println("学生集合中是否包含Eve：" + studentSet.contains(new Student("Eve", 20)));

        // 删除学生对象
        studentSet.remove(new Student("Charlie", 18));
        System.out.println("删除学生Charlie后的集合：" + studentSet);

        // 使用迭代器遍历学生集合
        Iterator<Student> iterator = studentSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    // 学生类，实现Comparable接口用于比较和排序
    static class Student implements Comparable<Student> {
        private String name;
        private int age;

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public int compareTo(Student other) {
            // 按照年龄进行排序
            return Integer.compare(this.age, other.age);
        }

        @Override
        public String toString() {
            return name + " (" + age + ")";
        }
    }
}
